<?php

/**
 *  合同管理
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 10:02
 */

namespace app\api\controller\contractmanage;

use think\Controller;
use PhpOffice\PhpWord\TemplateProcessor;
use app\api\controller\common\CommonPlus;
// use think\console\command\make\Controller;  


class Contractmgr extends Controller
{

    // <s></s>
    protected $admin;
    protected $model = null;
    protected $statusArr = [0=>'未处理',1=>'通过',2=>'拒绝'];
    protected $backArr = [0=>'未回传',1=>'已回传'];
    public function _initialize()
    {
        $this->admin = session('admin');
        $this->model = model('Contractmgr');
    }

    /**
     * 合同管理列表页
     * 模糊查询需后补 暂时先做普版 原先
     */
    public function contractList999()
    {
        //var_dump(23);die;
        $keyword = input('keyword');
        $id_zs = input('id_zs'); // 展商id
        $id_zhui = input('id_zhui'); //展会id
        $page = input('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0;
        if (!empty($id_zs)) {
            $where['id_zs'] =  $id_zs;
        }
        if (!empty($id_zhui)) {
            $where['id_zhui'] =  $id_zhui;
        }


        if (!empty($keyword)) {
            $where['title|title_en'] = array('like', '%' . $keyword . '%');
        }

        $list = $this->model->listWherePage($where, 'id desc', ($page - 1) * $pagesize, $pagesize);
        $total = $this->model->countWhere($where);

        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'total' => $total, 'countpage' => ceil($total / $pagesize)]]);
    }

    /**
     * 合同列表 多关联
     */
    public function contractList(){
        $exhibition = $this->request->param('exhibition');
        if(empty($exhibition)){
            return json(['code'=>-1,'msg'=>'缺少关键主键展会id']);
        }
        $zs_name=$this->request->param('zs_name');
        $zs_name = isset($zs_name) && $zs_name != '' ? $zs_name : '';
        $status = $this->request->param('status');
        $status = isset($status) && $status != '' ? $status : -1;
        $page = $this->request->param('page');
        $page = isset($page) && $page != '' ? $page : 1;
        $back = input('back');
        $back = isset($back) && $back != '' ? $back : -1;
        $member_id = input('member_id');
        $member_id = isset($member_id) && $member_id != '' ? $member_id : '';
        $pageSize = input('pageSize');
        $pageSize = isset($pageSize) && $pageSize != '' ? $pageSize : 10;

        $where['h.is_delete'] = 0;
        if(!empty($exhibition)){
            $where['h.id_zhui'] = $exhibition;
        }

        if(!empty($zs_name)){
            $where['h.name_zs'] = array('like','%'.$zs_name.'%');
        }

        if(is_numeric($back)&&$back>=0){
            $where['h.is_back'] = $back;
        }

        if(is_numeric($status)&&$status>=0){
            $where['h.s_status'] = $status;
        }

        if(is_numeric($member_id)&&$member_id>0){
            $where['h.create_uid'] = $member_id;
        }else{
            //当前用户权限
            $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
            if(!$role_id && $this->admin['is_super']==0){
                return json(['code'=>0,'msg'=>'角色不存在']);
            }
            $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
            if($this->admin['is_super'] == 1){
                //不加限制条件
            }else{
                if($is_gl == 1){
                    $w['org_id_tree'] = ['like', "%".$this->admin['org_id']."%"];
                    //所有所属组织的用户 id
                    $adminarr =db('admin')->field('id')->where($w)->select();
                    $admin_ids = array_column($adminarr,'id');
                    $where['h.create_uid'] = array('in',$admin_ids);
                }else{
                    $where['h.create_uid'] = $this->admin['id'];
                }
            }
        }


        $page = max(1,intval($page));
        $list = db('contract')
            ->alias('h')
            ->field('h.*,e.id exhibition_id,e.title,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->order('id desc')
            ->limit(($page-1)*$pageSize.','.$pageSize)
            ->select();

        $total = db('contract')
            ->alias('h')
            ->field('h*,e.id as exhibition_id,e.name,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->count();

        if(!empty($list)){
            foreach ($list as &$v){
                $ftotal=db('finance')->field('sum(total_fee) as f_total')->where(['contract_id'=>$v['id']])->select();
                $v['f_total'] =  empty($ftotal)?'0.00':$ftotal[0]['f_total'];
            }
            unset($v);
        }

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);

    }
    /**
     * 合同基本信息
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function contractDetail()
    {
        $com = new CommonPlus();
        $id = input('id');

        $where['id'] = $id;
        //$where['is_delete'] = 0;
        $info = $this->model->findWhere($where);

        // 获取 D表
        $where1 = array('mid' => $id,'is_delete'=>0);
        $r1 = $com->sel_com_fxlist("f", $where1, "contract_detail");
        $info['D_detail'] = $r1; // 表单的明细

        $r2 = $com->sel_com_fxlist("f", $where1, "contract_detail_plan");
        $info['plan_detail'] = $r2; // 付款计划 明细条数
        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }


    /**
     * 新增合同
     * 缺少文件转doc
     * 具体要实现什么样的》》》
     * 2：应该还需要合同的明细表
     *
     * @return \think\response\Json|void
     */
    public function addContract()
    {
        $com = new CommonPlus();

        //==common
        $create_uid = $this->admin['id'];
        $remark = input('remark');
        //== comon
        $name_zs = input('name_zs'); //展商名称:
        $id_zs = input('id_zs'); //展商id
        if(empty($id_zs)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展商']);
        }
        $id_zhui = input('id_zhui'); //展会id
        if(empty($id_zhui)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展会']);
        }
        $id_zwei = input('id_zwei'); //展位id
        if(empty($id_zwei)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展位']);
        }
        $addr = input('addr');
        $tel = input('tel');
        $fax = input('fax');  // 传真
        $people_jinban = input('people_jinban'); //经办人
        $type_canzhan = input('type_canzhan'); // 参展展品类别
        $ht_id = input('ht_id'); // 合同编号
        $ht_name = input('ht_name'); // 合同名称
        $people_qianyue = input('people_qianyue'); // 签约人
        $customername = input('customername'); // 客户名称
        $ht_time = strtotime(input('ht_time')); // 合同日期
        $ht_time_endpay = strtotime(input('ht_time_endpay')); // 付款截止日期
        $money_total_xiangmu = input('money_total_xiangmu'); // 项目总金额
        $money_zhuce = input('money_zhuce'); // 注册费
        $money_total_ht = input('money_total_ht'); // 合同总金额
        $pay_planname = input('pay_planname'); // 付款计划名称
        $money_pay_one = input('money_pay_one'); // 单笔支付
        $money_pay_total_fk = input('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = strtotime(input('time_pay_endfk')); // 付款截至日期
        $per_fk = input('per_fk'); // 付款比例
        $htmodel = input('htmodel'); // 获取选择的合同模版
        $link=input('link'); // 网址
        $positions_cn=input('positions_cn'); // 职位
        $email_person=input('email_person'); // email
        $business_type=input('business_type'); // 公司性质
        $mobile_person=input('mobile_person'); // 移动电话
        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'create_time' => time(),'htmodel'=>$htmodel,
            'name_zs' => $name_zs, 'id_zs' => $id_zs, 'id_zhui' => $id_zhui, 'id_zwei'=>$id_zwei,'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk,'is_back'=>0,'s_status'=>0,'link' => $link,'positions_cn'=>$positions_cn,'email_person'=>$email_person,'business_type'=>$business_type,'mobile_person'=>$mobile_person
        );


        $r = $this->model->insertData($data);
        //var_dump($r );die;
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        // //添加关联的合同表中----李  晨--建立
        // $datas['contract_id'] = $r;
        // $datas['exhibition_id'] = $id_zhui;
        // $datas['booth_id'] = $id_zwei;
        // $datas['company_id'] = $id_zs;
        // $datas['member_id'] = $create_uid;
        // $datas['is_pay'] = 0;
        // $datas['status'] = 0;
        // $datas['back'] = 0;
        // $datas['create_time'] = time();
        // $rDatas = model('CompanyFollowContract')->insertData($datas);
        // if(!$rDatas){
        //     return json(['code'=>0,'msg'=>'操作失败，请重试']);
        // }



        // 明细 开始

        /**
         * 服务类别  下拉框 还是文本框？？？
         * sort 是永远 递增
         */
        // 测试
        $detaildata11 = array(
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "2.00", "price_sale" => "7", "discount" => "1.5", "num" => "10", "price_prate" => "2", "price_count" => "110", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "30.00", "price_sale" => "8", "discount" => "1.2", "num" => "20", "price_prate" => "3", "price_count" => "115", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "40.00", "price_sale" => "9", "discount" => "1.3", "num" => "30", "price_prate" => "5", "price_count" => "98", "remark" => "remark"),
        );

        //增加明细   包含更新
        $detaildata1 = input('D_detail'); // 数组
        // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        $detaildata = json_decode($detaildata1, TRUE);
        // var_dump($detaildata);die;
        //$detaildata = 0;
        $z_id = $r; // 主id
        if (is_array($detaildata)) {
            $i = 0;
            foreach ($detaildata as $item) {
                $i++;
                $data_d = array(
                    'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],'isck' => $item['isck'],
                    //'type_serviceid' => $item['type_serviceid'],
                    'type_service' => $item['type_service'], 'price' => $item['price'],
                    'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
                    'price_count' => $item['price_count'], 'remark' => $item['remark']
                );
                $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


            }
        }


        // 明细end

        // 计划明细
        $plan_detail22 = array(
            array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "7" ),
            array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "8" ),
        );

        //增加明细   包含更新  计划 表 不一样

        // $plan_detail = json_decode(json_encode(($plan_detail22)),TRUE); // ces
        $plan_detail1 = input('plan_detail'); // 数组
        $plan_detail = json_decode($plan_detail1, TRUE);
        //$detaildata = 0;
        $z_id = $r; // 主id
        if (is_array($plan_detail)) {
            $i = 0;
            foreach ($plan_detail as $item) {
                $i++;
                $data_d = array(
                    'mid' => $z_id, 'sortid' => $i, 'plan_name' => $item['plan_name'], 'money_db' => $item['money_db'],
                    'money_total' => $item['money_total'], 'time_fked' => strtotime($item['time_fked']), 'per_fk' => $item['per_fk']
                );
                $r2 = $this->model->insertData_D($data_d, 'contract_detail_plan'); // coms


            }
        }
        // 明细end

        // 0404 测试  查询展位


        $where = array('id' => $id_zwei);
        $rzw = $com->sel_com_fxlist("f", $where, "booth");

        // $pricezh=$com->convertAmountToCn($rzw[0]['price'],0);
        $pricezhdax=$com->inttod($rzw[0]['price'],0);
        $zspara=array('id_zs'=>$id_zs); // zhans
        $info_zs= $com->getinfo_zs( $zspara);// 展商id...

        // 0404

        // 根据模版 转doc 2：回头在更新主表new file

        if (!empty($htmodel)) {
            $data['htmodel'] = $htmodel;
            $data['z_id'] = $r;
            // 0404
            // 展商信息 可能又重复数组 覆盖，排查
            $data['company_name'] = $info_zs[0]['company_name']; //
            $data['company_name_en'] = $info_zs[0]['company_name_en']; //
            $data['company_address'] = $info_zs[0]['company_address']; //
            $data['company_yb'] = $info_zs[0]['company_yb']; //   邮编
            $data['link'] = $info_zs[0]['link']; //
            $data['salesman'] = $info_zs[0]['salesman']; //   负责人 暂时业务员
            $data['positions'] = $info_zs[0]['positions']; //    职务
            $data['tel'] = $info_zs[0]['tel']; //
            $data['mobile'] = $info_zs[0]['mobile']; //
            $data['fax_person'] = $info_zs[0]['fax_person']; //     传真
            $data['email'] = $info_zs[0]['email']; //


            //2
            $data['area'] = $rzw[0]['area']; // 面积
            $data['price'] = $rzw[0]['price'];
            $data['price_count'] = $rzw[0]['price'];
            $data['price_daxie'] =  $pricezhdax; // 大写
            $items = $data;
            // 记录主表filepath
            $reshtmodel = $this->formbuilddoc("ff", $items);  //转 doc
        }
        // var_dump( $reshtmodel );die;
        // 发的发的发

        return json(['code' => 1, 'msg' => '操作成功', 'z_id' => $r]);die;
    }

    /**
     * 也是需要编辑明细的D表  这个回头在说
     *
     */
    public function editContract()
    {

        $com = new CommonPlus();
        $id = input('id');
        //==common
        $create_uid = $this->admin['id'];
        $remark = input('remark');
        //== comon
        $name_zs = input('name_zs'); //展商名称:
        $id_zs = input('id_zs'); //展商id
        $id_zhui = input('id_zhui'); //展会id
        $id_zwei = input('id_zwei'); //展位id
        $addr = input('addr');
        $tel = input('tel');
        $fax = input('fax');  // 传真
        $people_jinban = input('people_jinban'); //经办人
        $type_canzhan = input('type_canzhan'); // 参展展品类别
        $ht_id = input('ht_id'); // 合同编号
        $ht_name = input('ht_name'); // 合同名称
        $people_qianyue = input('people_qianyue'); // 签约人
        $customername = input('customername'); // 客户名称
        $ht_time = strtotime(input('ht_time')); // 合同日期
        $ht_time_endpay = strtotime(input('ht_time_endpay')); // 付款截止日期
        $money_total_xiangmu = input('money_total_xiangmu'); // 项目总金额
        $money_zhuce = input('money_zhuce'); // 注册费
        $money_total_ht = input('money_total_ht'); // 合同总金额
        $pay_planname = input('pay_planname'); // 付款计划名称
        $money_pay_one = input('money_pay_one'); // 单笔支付
        $money_pay_total_fk = input('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = strtotime(input('time_pay_endfk')); // 付款截至日期
        $per_fk = input('per_fk'); // 付款比例
        $htmodel = input('htmodel'); // 获取选择的合同模版
        $link=input('link'); // 网址
        $positions_cn=input('positions_cn'); // 职位
        $email_person=input('email_person'); // email
        $business_type=input('business_type'); // 公司性质
        $mobile_person=input('mobile_person'); // 移动电话
        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'create_time' => time(),'htmodel'=>$htmodel,
            'name_zs' => $name_zs, 'id_zs' => $id_zs, 'id_zhui' => $id_zhui, 'id_zwei'=>$id_zwei,'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk,'link' => $link,'positions_cn'=>$positions_cn,'email_person'=>$email_person,'business_type'=>$business_type,'mobile_person'=>$mobile_person
        );


        // $data11 = array(
        //     'create_uid' => $create_uid, 'remark' => $remark, 'update_time' => time(),
        //     'name_zs' => $name_zs, 'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
        //     'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
        //     'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
        //     'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
        //     'per_fk' => $per_fk
        // );

        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data, $where);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }



        // 明细 开始

        /**
         * 服务类别  下拉框 还是文本框？？？
         * sort 是永远 递增
         */


        //增加明细   包含更新
        $detaildata1 = input('D_detail'); // 数组
        // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        $detaildata = json_decode($detaildata1, TRUE);
        // var_dump($detaildata);die;
        $detaildata = 0;
        $z_id = $id; // 主id
        if (is_array($detaildata)) {
            $i = 0;
            foreach ($detaildata as $item) {
                $i++;
                $data_d = array(
                    'is_delete'=>0,
                    'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],'isck' => $item['isck'],
                    //'type_serviceid' => $item['type_serviceid'],
                    'type_service' => $item['type_service'], 'price' => $item['price'],
                    'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
                    'price_count' => $item['price_count'], 'remark' => $item['remark']
                );
                $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


            }
        }
        // 明细end

        // 计划明细
        $plan_detail22 = array(
            array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "7" ),
            array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "8" ),
        );

        //增加明细   包含更新

        // $plan_detail = json_decode(json_encode(($plan_detail22)),TRUE); // ces
        $plan_detail1 = input('plan_detail'); // 数组
        $plan_detail = json_decode($plan_detail1, TRUE);
        $plan_detail = 0; // 走单独的小按钮保存

        if (is_array($plan_detail)) {
            $i = 0;
            foreach ($plan_detail as $item) {
                $i++;
                $data_d = array(
                    'is_delete'=>0,
                    'mid' => $z_id, 'sortid' => $i, 'plan_name' => $item['plan_name'], 'money_db' => $item['money_db'],
                    'money_total' => $item['money_total'], 'time_fked' => strtotime($item['time_fked']), 'per_fk' => $item['per_fk']
                );
                $r2 = $this->model->insertData_D($data_d, 'contract_detail_plan'); // coms


            }
        }
        // 明细end


        // 0404 测试  查询展位


        $where = array('id' => $id_zwei);
        $rzw = $com->sel_com_fxlist("f", $where, "booth");

        // $pricezh=$com->convertAmountToCn($rzw[0]['price'],0);
        $pricezhdax=$com->inttod($rzw[0]['price'],0);
        $zspara=array('id_zs'=>$id_zs); // zhans
        $info_zs= $com->getinfo_zs( $zspara);// 展商id...

        // 0404



        // 根据模版 转doc 2：回头在更新主表new file
        if (!empty($htmodel)) {
            $items['htmodel'] = $htmodel;
            $items['z_id'] = $r;
            // 0404
            // 展商信息 可能又重复数组 覆盖，排查
            $items['company_name'] = $info_zs[0]['company_name']; //
            $items['company_name_en'] = $info_zs[0]['company_name_en']; //
            $items['company_address'] = $info_zs[0]['company_address']; //
            $items['company_yb'] = $info_zs[0]['company_yb']; //   邮编
            $items['link'] = $info_zs[0]['link']; //
            $items['salesman'] = $info_zs[0]['salesman']; //   负责人 暂时业务员
            $items['positions'] = $info_zs[0]['positions']; //    职务
            $items['tel'] = $info_zs[0]['tel']; //
            $items['mobile'] = $info_zs[0]['mobile']; //
            $items['fax_person'] = $info_zs[0]['fax_person']; //     传真
            $items['email'] = $info_zs[0]['email']; //


            //2
            $items['area'] = $rzw[0]['area']; // 面积
            $items['price'] = $rzw[0]['price'];
            $items['price_count'] = $rzw[0]['price'];
            $items['price_daxie'] =  $pricezhdax; // 大写
            // 记录主表filepath
            $res = $this->formbuilddoc("ff", $items);  //转 doc


        }


        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 删除项目
     * 1：列表 删除 是不是同时要删除子表。这个是大的删除
     * 2：合同主项 里面要依次删除呢？需要重写方法fsd
     */
    public function delContract()
    {
        $id = input('id');
        if(empty($id)){
            return json(['code' => 0, 'msg' => '缺少关键主键合同id']);
        }
        $where = ['id' => $id];
        $info = $this->model->where($where)->find();
        if (empty($info)) {
            return json(['code' => 0, 'msg' => '记录不存在，请核实']);
        };
        if($info['s_status'] == 0 || $info['s_status'] == 1){
            return json(['code' => 0, 'msg' => '合同审核或未完成无法此操作']);
        }
        if($info['create_uid'] != $this->admin['id']){
            return json(['code' => 0, 'msg' => '你不是合同创建者无法此次操作']);
        }
        $r = $this->model->deleteWhere(['id' => $id]);
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }



    /**
     * 合同 明细 副表 走单独接口 明细
     * @return \think\response\Json|void
     */
    public function editContract_d_ht()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型 no go
        $mid= input('mid');
        $sortid = input('sortid');

        $updates = array(
            'issort'=>1,'mid'=>$mid,
            'pro_name' => input('pro_name'), 'type1_name' =>input('type1_name'),
            'type_service' => input('type_service'), 'price' =>  input('price'),
            'price_sale' =>  input('price_sale'), 'discount' =>  input('discount'),
            'num' =>  input('num'), 'price_prate' =>  input('price_prate'),
            'price_count' =>  input('price_count'), 'remark' => input('remark')
        );


        $where1 = array('mid' => $mid,'sortid'=>$sortid);
        $dbname="contract_detail";

        $r = $com->insert_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 合同 明细 副表 走单独接口 明细 dd
     * @return \think\response\Json|void
     * 计划名称|单笔支付\money_total|付款截止日期|付款比例
     */
    public function editContract_d_plan()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型 no go
        $mid= input('mid');
        $sortid = input('sortid');

        $updates = array(
            'issort'=>1,'mid'=>$mid,
            'plan_name' => input('plan_name'), 'money_db' =>input('money_db'),
            'money_total' => input('money_total'), 'time_fked' =>  strtotime(input('time_fked')),
            'per_fk' => input('per_fk')
        );


        $where1 = array('mid' => $mid,'sortid'=>$sortid);
        $dbname="contract_detail_plan";

        $r = $com->insert_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => 'success']);
    }



    /**
     * 合同删除 明细
     * formtype
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function delContract_d_com()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型
        $mid= input('mid');
        $sortid = input('sortid');

        if(empty($formtype)){
            return json(['code' => 0, 'msg' => '缺少参数fromtype']);
        }

        $where1 = array('mid' => $mid,'sortid'=>$sortid); //保持一致
        $updates= array('is_delete' => 1); //保持一致

        $dbname="";
        if($formtype=="d_ht"){
            // 合同明细d
            $dbname="contract_detail";
        }elseif($formtype=="d_plan"){
            //  计划明细d
            $dbname="contract_detail_plan";
        }

        $r = $com->edit_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 支持单独的子表操作
     * 是否在页面添加按钮 允许此操作？？
     * 赞不开启
     *
     */
    public function delContract_d()
    {

        $mid = input('mid');
        $sortIds = input('sortids');
        foreach ($sortIds as $item) {
            $r = $this->model->deleteWhere_d(['sortid' => $item, 'mid' => $mid]);
        }

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }
    /**
     *  查询合同模版列表 供存档用
     * 主要  添加合同要生成模版。有新模版就继续手动编辑变量。然后 上传 追来源
     * com sel  一些基础传参
     */
    public function sel_htmode()
    {
        $com = new CommonPlus();
        $where = array('is_delete' => 0);
        $r = $com->sel_com_fxlist("f", $where, "contract_mould_yc");

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功', 'data' => $r]);
    }

    /**
     * 生成合同模版 新增调用
     * ${keti} tag
     * 替换 形成 新文件，并更新主表 存储 log
     * 前端应该下拉框与后台保持一致；
     *
     */
    public function formbuilddoc($type, $items)
    {
        $doc = new CommonPlus();
        $Billno = $doc->createNO('HT-', 1);
        $filenewname = $Billno . '.docx';
        $comptype = "DZ";
        $comptype1 = $comptype == "MY" ? "Y" : "";
        $comptype2 = $comptype == "HZ" ? "Y" : "";
        $comptype3 = $comptype == "DZ" ? "Y" : "";
        $type = "HT";
        //$HTfile = array('modelfile' => '2019PLF-biaogaite.docx', 'newfile' => $filenewname);
        $HTfile = array('modelfile' => $items['htmodel'], 'newfile' => $filenewname);
        // 传参数过去 替换
        $params = array(
            "company_name" => $items['company_name'], "company_name_en" => $items['company_name_en'] , "company_address" =>$items['company_address'],
            "postcode" => $items['company_yb'],"link" => $items['link'],"contact" => $items['salesman'], "positions" => $items['positions'], "email" => $items['email'],
            "fax" => $items['fax_person'],
            "tel" =>$items['tel'], "mobile" =>$items['mobile'], "comptype1" => $comptype1, "comptype2" => $comptype2, "comptype3" => $comptype3,
            "area"=>$items['area'],"price"=>$items['price'],"price_count"=>$items['price_count'],"price_daxie"=>$items['price_daxie']
        );

        //$isfile = $doc->checkHTmodelfile($type, $HTfile['modelfile']);  // 检测
        // var_dump($params);die;
        $isfile = 2;
        if ($isfile > 0) {
            $res = $doc->dobuildDoc($type, $HTfile, $params);
            //var_dump( $res );die;
            if ($res['info']) {
                return json(['code' => 0, 'msg' => '合同生成失败']);
            } else {
                // return json(['code' => 1, 'msg' => '合同生成成功']);
                // 更新主表相关信息
                $data1 = array(
                    'htmodel' => $items['htmodel'], 'model_newfile' => $res['model_newfile']
                );
                $where['id'] = $items['z_id'];
                $r = $this->model->updateBywhere($data1, $where);
            }
        } else {
            return json(['code' => 0, 'msg' => '合同模板不存在']);
        }
    }




    /**
     * 生成合同模版 测试用
     * ${keti} tag
     * 替换 形成 新文件，
     * 前端应该下拉框与后台保持一致；
     */
    public function builddoc()
    {
        $doc = new CommonPlus();
        $Billno = $doc->createNO('HT-', 1);
        $filenewname = $Billno . '.docx';
        $comptype = "DZ";
        $comptype1 = $comptype == "MY" ? "Y" : "";
        $comptype2 = $comptype == "HZ" ? "Y" : "";
        $comptype3 = $comptype == "DZ" ? "Y" : "";
        $type = "HT";
        $HTfile = array('modelfile' => '2019PLF-biaogaite.docx', 'newfile' => $filenewname);
        // 传参数过去 替换
        $params = array(
            "company_name" => "苏州光辉", "company_name_en" => "suzhouugnagh", "company_address" => "苏州相城",
            "contact" => "张三", "link" => "www.baidu", "positions" => "科长", "email" => "184511852@qq.com",
            "tel" => "17625010777", "mobile" => "17625010778", "comptype1" => $comptype1, "comptype2" => $comptype2, "comptype3" => $comptype3
        );

        $isfile = $doc->checkHTmodelfile($type, $HTfile['modelfile']);
        // var_dump($isfile);die;
        // $isfile=2;
        if ($isfile > 0) {
            $res = $doc->dobuildDoc($type, $HTfile, $params);
            if ($res) {
                return json(['code' => 0, 'msg' => '合同生成失败']);
            } else {
                return json(['code' => 1, 'msg' => '合同生成成功']);
            }
        } else {
            return json(['code' => 0, 'msg' => '合同模板不存在']);
        }
    }


    // 测试
    public function companyList_shaixuan_ces()
    {
        //基础公司表
        //个人信息 中文姓名 职务 部门 手机 数据来源 所属洲 国家 省份 城市  公司中文名 地址 网址 固定电话 一级分类 二级分类
        //$keyword = $this->request->param('keyword');
        $page = $this->request->param('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 200;
        $where['is_delete'] = 0; //回头问下
        $exhibition_id = $this->request->param('exhibition_id');//展会id
        if(empty($exhibition_id)){
            return json(['code' => 0, 'msg' => '缺少关键主键展会id']);
        }
        // 查询 st 精确查询还是模糊 查询。。。。擦  都是必要的字段留着 其他的没卵用
        $name_cn = $this->request->param('name_cn'); //中文姓名
        $positions_cn = $this->request->param('positions_cn'); //职务
        $department_cn = $this->request->param('department_cn'); //职务
        $mobile = $this->request->param('mobile'); //手机
        $data_from = $this->request->param('data_from'); //数据来源
        $country = $this->request->param('country');//国家
        $province = $this->request->param('province');  //省份
        $area_city = $this->request->param('area_city');  //地级市
        $company_name = $this->request->param('company_name'); //公司中文名
        $tel = $this->request->param('tel');   //固定电话
        $link = $this->request->param('link'); //网址
        $category_id = $this->request->param('category_id');  //一级 分类
        $second_category_id = $this->request->param('second_category_id');     //二级 分类

        if(!empty($name_cn)){
            $where['name_cn'] = array('like', '%' . $name_cn . '%');
        }

        if(!empty($positions_cn)){
            $where['positions_cn'] = array('like', '%' . $positions_cn . '%');
        }

        if(!empty($department_cn)){
            $where['positions_cn'] = array('like', '%' . $department_cn . '%');
        }

        if(!empty($mobile)){
            $where['mobile'] = $mobile;
        }

        if(!empty($data_from)){
            $where['data_from'] = array('like', '%' . $data_from . '%');
        }

        if(!empty($country)){
            $where['data_from'] = array('like', '%' . $country . '%');
        }

        if(!empty($province)){
            $where['data_from'] = array('like', '%' . $province . '%');
        }

        if(!empty($area_city)){
            $where['data_from'] = array('like', '%' . $area_city . '%');
        }

        if(!empty($company_name)){
            $where['company_name'] = array('like', '%' . $company_name . '%');
        }

        if(!empty($tel)){
            $where['tel'] = $tel;
        }

        if(!empty($link)){
            $where['tel'] = $link;
        }

        if(!empty($category_id)){
            $where['category_id'] = array('like', '%' . $category_id . '%');
        }

        if(!empty($second_category_id)){
            $where['company_name'] = array('like', '%' . $second_category_id . '%');
        }
        $list =db('company')->field('id,company_name')->where($where)->order('id desc')->limit(($page-1)*$pagesize.','.$pagesize)->select();
        $total=db('company')->where($where)->count();
        $w['exhibition_id'] = $exhibition_id;
        $newList=array();
        //1; 2；排除 企业库 存在于 公海的数据 200526

        foreach($list as &$val){
            $w['company_id']=$val['id'];
            $ls = $this->model->field('company_id')->where($w)->select();
            if(empty($ls)){
                $val['is_pub']=0;
                $newList[]=$val;
            }else{
                //$val['is_pub']=1;
            }
        }
        unset($val);
        $list=$newList;  //st
        $total=count($list); //st
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'total' => $total]]);
    }

    // the ed

}
